//
//  KLMCreateHomeController.swift
//  KLM_GN
//
//  Created by Nic on 2025/3/14.
//

import UIKit


private let roomCellId = String(describing: KLMBaseRowItemCell.self)
//private let addCellId = String(describing: UITableViewCell.self)

class KLMCreateHomeController: KLMBaseController {

    @IBOutlet weak var homeView: UIView!
    @IBOutlet weak var cityView: UIView!
    
    @IBOutlet weak var nameLabel: UILabel!
    @IBOutlet weak var textField: UITextField!
    @IBOutlet weak var lineView: UIView!
    @IBOutlet weak var cityLabel: UILabel!
    @IBOutlet weak var tapLabel: UILabel!
    @IBOutlet weak var arrowBtn: UIButton!
    @IBOutlet weak var roomLabel: UILabel!
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var tableViewHCons: NSLayoutConstraint!
    
    weak var saveBtn: KLMBaseButton?
    
    var rooms: [KLMRowItem] = {
        KLMRowItem.createHomeRooms()
    }()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = rgba(243, 243, 246, 1)
        
        let item = KLMBaseButton()
        saveBtn = item
        navigationItem.rightBarButtonItem = UIBarButtonItem.itemWithBaseButton(item, target: self, action: #selector(saveHome(_:)), configBlock: { baseItem in
            baseItem.isEnabled = false
            baseItem.configStyle(with: KLMLocalizable.LANGLOC("Save"), font: UIFont(safeName: "PingFangSC-Bold", size: 18), titleColor: appMainThemeColor)
            baseItem.configStyle(titleColor: appMainThemeColor.withAlphaComponent(0.5), state: .disabled)
        })
    }
    
    @objc func saveHome(_ item: KLMBaseButton) {
        
        let roomNames = rooms.filter { $0.isOn }.compactMap({ $0.title})
        SVProgressHUD.show()
        KLMRequest.createHome(meshName: textField.text!, cityName: "", homeRoomNameList: roomNames) { response in
            
            let meshId: Int = response as! Int
            /// 本地存储新建的家庭ID
            KLMUserDefault.setValue(for: .currentSelectedHomeId, with: meshId)
            /// 广播消息
            NotificationCenter.post(.createHomeSuccess, userInfo: [NotificationKey.createHomeKey: meshId])
            
            let modalVc = KLMBaseModalController(type: .tipOnlyTitle, operTitle: "家庭创建成功", message: "完成", textFieldTip: "查看家庭", cancelTitle: "查看家庭", confirmTitle: "完成") { [weak self] in
                guard let self = self else { return }
                let homeVc = KLMHomeSettingController(homeId: meshId)
                self.navigationController?.popViewController(animated: false)
                self.navigationController?.pushViewController(homeVc, animated: true)
                print(self.navigationController ?? "")
                
            } confirmBlock: { [weak self] text, type in
                   guard let self = self else { return }
                handlePopAnimate()
                   
            }

            
//            let modalVc = KLMBaseModalController(type: .tipOnlyTitle, operTitle: "家庭创建成功", cancelTitle: "完成", confirmTitle: "查看家庭", cancelBlock: { [weak self] in
//                guard let self = self else { return }
//                handlePopAnimate()
//                
//            }, confirmBlock:  { [weak self] text, type in
//                guard let self = self else { return }
//                
//                let homeVc = KLMHomeSettingController(homeId: meshId)
//                self.navigationController?.popViewController(animated: false)
//                self.navigationController?.pushViewController(homeVc, animated: true)
//                print(self.navigationController ?? "")
//            })
            self.modalVc(vc: modalVc)
            
//            KLMService.addGroup(meshId: meshId, groupName: "所有设备", groupType: 3) { response in
//                KLMLog("分组提交成功到服务器")
//
//                SVProgressHUD.showSuccess(withStatus: KLMLocalizable.LANGLOC("Success"))
//                DispatchQueue.main.asyncAfter(deadline: 1) {
//                    NotificationCenter.default.post(name: .homeAddSuccess, object: nil)
//                    self.navigationController?.popViewController(animated: true)
//                }
//            } failure: { error in
//                KLMHttpShowError(error)
//            }
            
        } failure: { error in
            KLMHttpShowError(error)
        }
    }
    
    @objc private func handlePopAnimate() {
        guard let navController = navigationController,
              let tabBarController = self.tabBarController else { return }
        
        let tabBar = tabBarController.tabBar
        let originalTransform = tabBar.transform
        navController.popToRootViewController(animated: true)
        
//        UIView.animate(withDuration: 0.6, delay: 0, options: [.curveLinear]) {
//            let translationX = -tabBar.bounds.width * CGFloat(tabBarController.selectedIndex)
//            tabBar.transform = CGAffineTransform(translationX: translationX, y: 0)
//            
//        } completion: { _ in
//            tabBarController.selectedIndex = 0
//            
//            UIView.animate(withDuration: 0.3) {
//                tabBar.transform = originalTransform
//            }
//        }
        
        UIView.animate(withDuration: 0.6, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.5) {
            let translationX = -tabBar.bounds.width * CGFloat(tabBarController.selectedIndex)
            tabBar.transform = CGAffineTransform(translationX: translationX, y: 0)
        } completion: { _ in
            tabBarController.selectedIndex = 0
            UIView.animate(withDuration: 0.3) {
                tabBar.transform = originalTransform
            }
        }
    }
    
    override func viewDidLoadConfig() {
        super.viewDidLoadConfig()
        // 完整字符串
        let fullString = "家庭名称*"
        let attributedString = NSMutableAttributedString(string: fullString)
        attributedString.addAttributes([.foregroundColor: rgba(38, 38, 38, 1)], range: NSRange(location: 0, length: fullString.count - 1))
        attributedString.addAttributes([.foregroundColor: rgba(253, 55, 59, 1)], range: NSRange(location: fullString.count - 1, length: 1))
        nameLabel.attributedText = attributedString
        nameLabel.font = UIFont(safeName: "PingFangSC-Medium", size: 16)
        
        //rgba(253, 55, 59, 1)
        cityLabel.configStyle(with: "城市位置", font: UIFont(safeName: "PingFangSC-Medium", size: 16), titleColor: rgba(38, 38, 38, 1))
        textField.attributedPlaceholder = NSAttributedString(string: "填写", attributes: [.foregroundColor: rgba(229, 229, 229, 1), .font: UIFont(safeName: "PingFangSC-Medium", size: 16) ?? UIFont.systemFont(ofSize: 16)])
        textField.addTarget(self, action: #selector(textChanged(_:)), for: .editingChanged)
        
        lineView.backgroundColor = rgb(229, 229, 229)
        tapLabel.configStyle(with: "设定", font: UIFont(safeName: "PingFangSC-Medium", size: 16), titleColor: rgb(229, 229, 229))
        roomLabel.configStyle(with: "房间", font: UIFont(safeName: "PingFangSC-Medium", size: 12), titleColor: rgba(129, 129, 129, 1))
        
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(tapSetCity(_:)))
        tapLabel.isUserInteractionEnabled = true
        tapLabel.addGestureRecognizer(tapGesture)
        
        let cornerRadius: CGFloat = 8
        homeView.backgroundColor = .white
        homeView.layer.cornerRadius = cornerRadius
        homeView.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
        homeView.layer.masksToBounds = true
        
        cityView.backgroundColor = .white
        cityView.layer.cornerRadius = cornerRadius
        cityView.layer.maskedCorners = [.layerMinXMaxYCorner, .layerMaxXMaxYCorner]
        cityView.layer.masksToBounds = true
        
        tableView.register(UINib(nibName: "KLMBaseRowItemCell", bundle: nil), forCellReuseIdentifier: roomCellId)
        tableView.backgroundColor = .white
        tableView.layer.cornerRadius = cornerRadius
        tableView.layer.masksToBounds = true
        tableView.showsVerticalScrollIndicator = false
        tableView.separatorStyle = .none
        tableView.dataSource = self
        tableView.delegate = self
    }
    @objc func tapSetCity(_ label: UILabel) {
        print("设定...")
    }
    
    @objc func textChanged(_ sender: UITextField) {
        saveBtn?.isEnabled = sender.text != nil && !sender.text!.isEmpty
    }
    
    override func layoutConfig() {
        super.layoutConfig()
        tableView.layoutIfNeeded()
        let maxH = view.height - tableView.y - CGFloat(KLM_BottomSafeAreaHeight)
        let contentH = tableView.contentSize.height
        tableViewHCons.constant = min(maxH, contentH)
        tableView.isScrollEnabled = contentH > maxH
        
        print("tableView.contentSize.height", tableView.contentSize.height)
    }
}


extension KLMCreateHomeController: UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return rooms.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = KLMBaseRowItemCell.cell(with: tableView, at: indexPath, cellId: roomCellId)
        cell.backgroundColor = .clear
        cell.item = rooms[indexPath.row]
        cell.showLine = cell.item.type == .addRoom
        cell.setFont(UIFont(safeName: "PingFangSC-Medium", size: 16))
        cell.delegate = self
        return cell
    }
}

extension KLMCreateHomeController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        UIView.animate(withDuration: 1.0) {
            tableView.deselectRow(at: indexPath, animated: true)
        }
        let item = rooms[indexPath.row]
        if item.type == .addRoom {
            /// 跳转到添加房间页面
        }
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 48
    }
}

extension KLMCreateHomeController: KLMBaseRowItemCellDelegate {
    func rowItemCellTapArrowBtn(cell: KLMBaseRowItemCell, index: IndexPath, on tableView: UITableView) {
        rooms[index.row].isOn = !rooms[index.row].isOn
        rooms[index.row].arrowIcon = rooms[index.row].isOn ? "Role_select" : "Role_no_select"
        
        tableView.reloadRows(at: [index], with: .fade)
    }
}
